﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;

namespace Koala.Pro.ViewModels
{
    public partial class FunctionListViewModel : BaseListViewModel<FunctionInfo, string, FunctionPagedDto>
    {
        [ObservableProperty]
        private TreeViewModel<CustomTreeNode> functionTreeModel = new TreeViewModel<CustomTreeNode>();

        public FunctionListViewModel(IFunctionService service)
            : base(service)
        {
            ExportFields = "Name,ControlID,SystemType_ID,SortCode";
        }

        [RelayCommand]
        public async Task GetTree()
        {
            string typeId = App.ViewModel.SystemType;
            SystemTypeInfo systemTypeInfo = await BLLFactory<ISystemTypeService>.Instance.GetAsync(typeId);
            if (systemTypeInfo != null)
            {
                CustomTreeNode topNode = new CustomTreeNode
                {
                    Name = systemTypeInfo.Name,
                    IsChecked = true
                };
                new List<FunctionInfo>();
                List<FunctionInfo> children = ((!App.ViewModel.IsSuperAdmin) ? (await BLLFactory<IFunctionService>.Instance.GetFunctionNodesByUser(App.ViewModel.UserInfo.Id, typeId)) : (await BLLFactory<IFunctionService>.Instance.GetTree(systemTypeInfo.Id)));
                List<CustomTreeNode> list = AddRecursive(children, topNode);
                FunctionTreeModel.TreeItems = list;
                FunctionTreeModel.FilteredTreeItems = new List<CustomTreeNode>(list);
            }
            NotifyChanged("FunctionTreeModel");
        }

        private List<CustomTreeNode> AddRecursive(List<FunctionInfo> children, CustomTreeNode parentNode = null)
        {
            List<CustomTreeNode> list = new List<CustomTreeNode>();
            foreach (FunctionInfo child in children)
            {
                CustomTreeNode customTreeNode = new CustomTreeNode
                {
                    Name = child.Name,
                    Id = child.Id
                };
                AddRecursive(child.Children, customTreeNode);
                list.Add(customTreeNode);
            }
            if (parentNode != null)
            {
                parentNode.Children = list;
                return new List<CustomTreeNode> { parentNode };
            }
            return list;
        }
    }
}
